package com.pig4cloud.pigx.user.liftcycle.started;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mongodb.client.result.UpdateResult;
import com.pig4cloud.pigx.common.customize.mongo.utils.MongoUtils;
import com.pig4cloud.pigx.user.entity.UserApiLockDuration;
import com.pig4cloud.pigx.user.mapper.UserApiLockDurationMapper;
import com.pig4cloud.pigx.user.mapstruct.UserApiLockDurationStruct;
import com.pig4cloud.pigx.user.mongo.entity.UserApiLockDurationMongo;
import com.pig4cloud.pigx.user.util.UserUtil;
import com.pig4cloud.pigx.user.vo.UserApiConfigVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 用户服务启动后预热缓存数据
 *
 * @since 2022/8/12 16:12
 */
@Slf4j
@Order(0)
@Component
@AllArgsConstructor
public class UserWarmUpCache implements ApplicationRunner {

	private final UserApiLockDurationMapper userApiLockDurationMapper;

	private final UserUtil userUtil;
	private final MongoTemplate mongo;

	@Override
	public void run(ApplicationArguments args) {
		// 预热Api配置
		apiConfig();

		// 预热Api封禁时长配置
		apiLockDuration();
	}

	/**
	 * 预热Api配置
	 *
	 * @since 2022/11/1 10:13
	 */
	private void apiConfig() {
		UserApiConfigVO apiConfig = userUtil.getApiConfig();
		userUtil.flushRedisApiConfig(apiConfig);
	}

	/**
	 * 预热Api封禁时长配置
	 *
	 * @since 2022/10/31 17:03
	 */
	private void apiLockDuration() {
		// 查询，更新缓存
		LambdaQueryWrapper<UserApiLockDuration> lambdaQuery = new LambdaQueryWrapper<>();
		List<UserApiLockDuration> list = userApiLockDurationMapper.selectList(lambdaQuery);
		// 如果没有数据，直接删除缓存中的币对信息
		if (CollectionUtils.isEmpty(list)) {
			mongo.dropCollection(UserApiLockDurationMongo.class);
		}

		// 转换
		List<UserApiLockDurationMongo> mongoList = UserApiLockDurationStruct.INSTANCE.list2MongoList(list);

		// 新增/修改
		mongoList.forEach(i -> {
			Criteria criteria = Criteria.where("id").is(i.getId());
			Query query = Query.query(criteria);
			Update update = MongoUtils.getUpdate(i);

			UpdateResult updateResult = mongo.upsert(query, update, UserApiLockDurationMongo.class);
			if (Objects.isNull(updateResult.getUpsertedId()) && updateResult.getMatchedCount() != 1) {
				log.error("MongoDB-缓存预热-Api封禁时长配置。更新失败，参数：{}。结果：{}", JSON.toJSONString(i), JSON.toJSONString(updateResult));
				System.exit(0);
			}
		});

		log.error("MongoDB-缓存预热-Api封禁时长配置。更新成功，条数：{}", list.size());
	}
}
